﻿using Bnbjoy.Business.Model.Dashboard;
using BnbjoyBackend.Site.ConstantsNS;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace BnbjoyBackend.Site.Security
{
    public class BaseFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Action被执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext) 
        {
            dynamic authedUserInfo = HttpContext.Current.Session[Constants.AuthedUserInfo] as dynamic;
            if (authedUserInfo != null)
            {
                string userId = authedUserInfo.userId;
                string accessToken = AuthorizedUserManager.Instance.AccessToken;
                var headInfoParam = new HeadInfoParam { UserId = userId };
                HttpPostResponse response = ServiceManager.Instance.PostServiceSync(accessToken, "dashboard/HeadInfo", JsonConvert.SerializeObject(headInfoParam));
                if (response.StatusCode == HttpStatusCode.OK && response.Content.Length > 0)
                {
                    HeadInfoResponse resObj = (HeadInfoResponse)JsonConvert.DeserializeObject<HeadInfoResponse>(response.Content);
                    if (resObj != null)
                    {
                        filterContext.HttpContext.Session[Constants.DashboardHeadInfo] = resObj;
                    }
                }
                else if (response.StatusCode == HttpStatusCode.InternalServerError)
                {
                    Debug.WriteLine("500错误");
                }
            }
            else 
            {
                HttpContext.Current.Response.RedirectToRoute(
                     new RouteValueDictionary{
                            { "Controller", "Account" },
                            { "Action", "Login" }});

            }
        }

        /// <summary>
        /// Action被执行以后执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext) 
        {
            
        }
    }
}